package com.sscl.baselibrary.exts

import android.app.Activity
import android.content.Context
import android.text.InputType
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.WindowManager
import android.widget.EditText
import java.lang.reflect.Method


/**
 * 隐藏系统键盘
 *
 * @param activity Activity
 */
fun EditText.hideSoftInputMethod(activity: Activity) {
    activity.window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
    val methodName = "setShowSoftInputOnFocus"
    val cls: Class<EditText> = EditText::class.java
    val setShowSoftInputOnFocus: Method
    try {
        setShowSoftInputOnFocus = cls.getMethod(methodName, Boolean::class.javaPrimitiveType)
        setShowSoftInputOnFocus.isAccessible = true
        setShowSoftInputOnFocus.invoke(this, false)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

fun EditText.showPassword(showPassword: Boolean) {
    if (showPassword) {
        this.inputType = InputType.TYPE_CLASS_TEXT
        //setTransformationMethod 支持将输入的字符转换，包括清除换行符、转换为掩码
        this.transformationMethod =
            HideReturnsTransformationMethod.getInstance()
    } else {
        this.inputType = InputType.TYPE_TEXT_VARIATION_PASSWORD
        this.transformationMethod = PasswordTransformationMethod.getInstance()
    }
    this.setSelection(this.text.toString().length)
}

/**
 * 设置输入框输入类型
 *
 * @param context 上下文
 * @param inputType 输入类型
 */
fun EditText.setInpType(context: Context, inputType: Int) {
    if (context is Activity) {
        context.window.setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
        )
    }
    this.inputType = inputType
    try {
        val cls = EditText::class.java
        val setShowSoftInputOnFocus: Method = cls.getMethod(
            "setShowSoftInputOnFocus", Boolean::class.javaPrimitiveType
        )
        setShowSoftInputOnFocus.isAccessible = true
        setShowSoftInputOnFocus.invoke(this, false)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

/**
 * 隐藏系统键盘
 *
 * @param activity Activity
 */
fun EditText.hideSoftInputMethod(context: Context) {
    if (context is Activity) {
        hideSoftInputMethod(context)
        return
    }
    val methodName = "setShowSoftInputOnFocus"
    val cls: Class<EditText> = EditText::class.java
    val setShowSoftInputOnFocus: Method
    try {
        setShowSoftInputOnFocus = cls.getMethod(methodName, Boolean::class.javaPrimitiveType)
        setShowSoftInputOnFocus.isAccessible = true
        setShowSoftInputOnFocus.invoke(this, false)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}